package com.awesome.core.support.security;

import com.awesome.common.AwesomeException;
import com.awesome.core.entity.User;
import com.awesome.core.service.IUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Objects;

/**
 * @Description 跟spring security 对接的用户查询接口
 * @Author Hongkai.Wang
 * @Date 2020/12/19 00:00
 */
@Component
public class AwesomeUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUserName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(String.format("username[%s] not found .", username));
        }

        return new org.springframework.security.core.userdetails.User(user.getNameEn(), user.getNameEn(),
            Collections.emptyList());
    }
}
